﻿using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleDemo.GetImg
{
    internal class GetImages
    {
        static readonly HttpClient client = new HttpClient();

        internal static async Task GetImageTask()
        {
            try
            {
                using (HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/"))
                {

                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    string contentType = response.Content.Headers.ContentType?.ToString();

                    if (contentType != null && contentType.StartsWith("image/"))
                    {
                        // 如果是图片，下载图片
                        await DownloadImageAsync(response, "downloaded_image.jpg");
                    }
                    else if (contentType != null && contentType == "application/json")
                    {
                        // 如果是 JSON，解析 JSON 数据
                        string jsonContent = await response.Content.ReadAsStringAsync();
                        //JObject jsonObject = JObject.Parse(jsonContent);
                        Console.WriteLine(jsonContent);
                    }
                    else
                    {
                        Console.WriteLine($"未知的内容类型: {contentType}");
                    }
                }
                ;
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }

        private static async Task DownloadImageAsync(HttpResponseMessage response, string fileName)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                await response.Content.CopyToAsync(fileStream);
            }
            Console.WriteLine($"图片已下载到: {fileName}");
        }
    }
}
